// main.js - 整合版

/* ================= 基础功能 ================= */
document.addEventListener('DOMContentLoaded', function() {
  // ------ 原有基础功能 ------
  // 示例：导航菜单切换
  const minMenu = document.getElementById('minmenu');
  const menuList = document.querySelector('.menu_list');
  if (minMenu && menuList) {
    minMenu.addEventListener('click', () => {
      menuList.classList.toggle('active');
    });
  }

  // 示例：开关灯模式
  const myRadio = document.getElementById('myRadio');
  if (myRadio) {
    myRadio.addEventListener('click', () => {
      document.body.classList.toggle('dark-mode');
      myRadio.classList.toggle('active');
    });
  }
});

/* ================= AI聊天功能 ================= */
document.addEventListener('DOMContentLoaded', function() {
  // ------ 元素选择器 ------
  const chatContainer = document.querySelector('.ai-chat-container');
  const chatMessages = document.querySelector('.chat-messages');
  const chatInput = document.querySelector('.chat-input');
  const sendButton = document.querySelector('.send-button');
  const voiceButton = document.querySelector('.voice-button');
  const imageViewer = document.querySelector('.image-viewer');
  const closeViewer = document.querySelector('.close-viewer');
  const recordsContainer = document.querySelector('.database-records-container');
  const recordsContent = document.querySelector('.records-content');
  const closeRecordsBtn = document.querySelector('.close-records-btn');

  // 如果不在AI页面则退出
  if (!chatContainer) return;
  
  // 关闭数据库记录显示
  if (closeRecordsBtn) {
    closeRecordsBtn.addEventListener('click', function() {
      recordsContainer.style.display = 'none';
    });
  }

  // ------ 核心功能 ------
  let isLoading = false;
  const userAvatarUrl = "../static/img/toux.jpg"; // 用户头像
  const aiAvatarUrl = "../static/img/pic1.jpg"; // AI头像
  
  // 预设问题和回答，用于快速响应常见问题
  const presetResponses = {
    '你好': '你好！我是二手商品智能助手，可以回答您关于二手车、电子产品等问题。请问有什么可以帮助您的？',
    '你是谁': '我是二手商品智能助手，专门为您提供二手商品相关的咨询和建议。',
    '价格': '二手商品价格受多种因素影响，包括使用年限、磨损程度、市场需求等。您想了解哪类二手商品的价格信息？',
    '二手车': '二手车交易需要注意车况检查、过户手续、保险转移等问题。您需要了解具体哪方面的信息？',
    '数码产品': '购买二手数码产品时，建议检查功能完整性、电池健康度，并确认是否有保修。您想了解哪种数码产品？'
  };

  // 检查是否支持语音识别
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
  let recognition;
  
  if (SpeechRecognition) {
    recognition = new SpeechRecognition();
    recognition.lang = 'zh-CN';
    recognition.continuous = false;
    recognition.interimResults = false;
    
    // 语音识别设置
    recognition.maxAlternatives = 3; // 提供多个替代识别结果
    
    // 语音识别完成事件
    recognition.onresult = function(event) {
      const speechResult = event.results[0][0].transcript;
      chatInput.value = speechResult;
      
      // 删除语音动画
      const voiceAnim = document.querySelector('.voice-animation');
      if (voiceAnim) voiceAnim.remove();
      
      // 自动提交有效语音内容
      if (speechResult.length > 2) {
        setTimeout(handleSendMessage, 500);
      }
    };
    
    recognition.onend = function() {
      voiceButton.classList.remove('recording');
      // 删除语音动画
      const voiceAnim = document.querySelector('.voice-animation');
      if (voiceAnim) voiceAnim.remove();
    };
    
    // 错误处理
    recognition.onerror = function(event) {
      console.error('语音识别错误:', event.error);
      voiceButton.classList.remove('recording');
      
      // 删除语音动画
      const voiceAnim = document.querySelector('.voice-animation');
      if (voiceAnim) voiceAnim.remove();
      
      // 显示错误通知
      let errorMsg = '语音识别失败';
      switch(event.error) {
        case 'no-speech':
          errorMsg = '没有检测到语音，请重试';
          break;
        case 'network':
          errorMsg = '网络连接错误，请检查网络';
          break;
        case 'not-allowed':
          errorMsg = '未获得麦克风权限，请允许访问';
          break;
        default:
          errorMsg = `语音识别错误: ${event.error}`;
      }
      
      addNotification(errorMsg);
    };
  }
  
  // 添加语音按钮点击事件
  if (voiceButton) {
    voiceButton.addEventListener('click', function() {
      if (!SpeechRecognition) {
        addNotification('您的浏览器不支持语音识别，请使用Chrome浏览器');
        return;
      }
      
      try {
        if (voiceButton.classList.contains('recording')) {
          // 正在录音，停止
          recognition.stop();
          voiceButton.classList.remove('recording');
          
          // 删除语音动画
          const voiceAnim = document.querySelector('.voice-animation');
          if (voiceAnim) voiceAnim.remove();
        } else {
          // 开始录音
          voiceButton.classList.add('recording');
          createVoiceAnimation();
          recognition.start();
        }
      } catch (e) {
        console.error('语音识别启动失败:', e);
        addNotification('语音识别启动失败，请重试');
        voiceButton.classList.remove('recording');
      }
    });
  }
  
  // 添加通知消息
  function addNotification(message) {
    // 删除现有通知
    const existingNotification = document.querySelector('.notification');
    if (existingNotification) existingNotification.remove();
    
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
      notification.classList.add('show');
      setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
      }, 3000);
    }, 10);
  }
  
  // 创建语音动画
  function createVoiceAnimation() {
    // 删除已存在的语音动画
    const existingAnim = document.querySelector('.voice-animation');
    if (existingAnim) existingAnim.remove();
    
    const voiceAnim = document.createElement('div');
    voiceAnim.className = 'voice-animation';
    
    // 添加波纹动画
    const waves = document.createElement('div');
    waves.className = 'voice-waves';
    waves.innerHTML = '<span></span><span></span><span></span>';
    
    // 添加麦克风图标
    const micIcon = document.createElement('div');
    micIcon.innerHTML = `
      <svg class="mic-icon" viewBox="0 0 24 24" fill="currentColor">
        <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
        <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
        <line x1="12" y1="19" x2="12" y2="23"/>
        <line x1="8" y1="23" x2="16" y2="23"/>
      </svg>
    `;
    
    // 添加状态文本
    const statusText = document.createElement('div');
    statusText.className = 'status';
    statusText.textContent = '正在聆听...';
    
    // 添加提示
    const tipText = document.createElement('div');
    tipText.className = 'tip';
    tipText.textContent = '点击任意处取消';
    
    voiceAnim.appendChild(waves);
    voiceAnim.appendChild(micIcon);
    voiceAnim.appendChild(statusText);
    voiceAnim.appendChild(tipText);
    
    // 点击动画取消录音
    voiceAnim.addEventListener('click', () => {
      if (recognition) {
        recognition.stop();
      }
      voiceAnim.remove();
    });
    
    document.body.appendChild(voiceAnim);
    return voiceAnim;
  }
  
  // 图片查看器
  if (imageViewer && closeViewer) {
    // 关闭图片查看器
    closeViewer.addEventListener('click', function(e) {
      e.stopPropagation();
      imageViewer.style.display = 'none';
    });
    
    // 点击空白区域也关闭
    imageViewer.addEventListener('click', function(e) {
      if (e.target === imageViewer) {
        imageViewer.style.display = 'none';
      }
    });
  }
  
  // 显示图片查看器
  function showImageViewer(imgUrl, caption) {
    if (!imageViewer) return;
    
    const imgElement = imageViewer.querySelector('img');
    const captionElement = imageViewer.querySelector('p');
    
    if (imgElement) imgElement.src = imgUrl;
    if (captionElement) captionElement.textContent = caption || '图片预览';
    
    imageViewer.style.display = 'flex';
  }
  
  // 格式化图片链接
  function formatMessageWithImages(text) {
    // 查找图片链接
    const imgRegex = /!\[(.*?)\]\((.*?)\)/g;
    const images = [];
    let match;
    
    // 提取所有图片链接
    while ((match = imgRegex.exec(text)) !== null) {
      images.push({
        description: match[1] || '图片',
        url: match[2]
      });
    }
    
    // 查找纯URL图片
    const urlImgRegex = /(https?:\/\/[^\s]+\.(jpg|jpeg|png|gif|webp))/gi;
    let urlMatch;
    
    while ((urlMatch = urlImgRegex.exec(text)) !== null) {
      images.push({
        description: '图片',
        url: urlMatch[1]
      });
    }
    
    return {
      text: text,
      images: images
    };
  }
  
  // 添加消息
  function addMessage(text, sender) {
    // 创建消息容器
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    // 添加头像
    const avatarDiv = document.createElement('div');
    avatarDiv.className = 'message-avatar';
    const avatarImg = document.createElement('img');
    avatarImg.src = sender === 'user' ? userAvatarUrl : aiAvatarUrl;
    avatarImg.alt = sender === 'user' ? '用户' : 'AI';
    avatarDiv.appendChild(avatarImg);
    
    // 添加内容
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content';
    
    // 如果是AI回复，进行格式化处理
    if (sender === 'ai' || sender === 'error') {
      // 设置错误消息的样式
      if (sender === 'error') {
        contentDiv.style.backgroundColor = '#ffebee';
        contentDiv.style.color = '#d32f2f';
      }
      
      // 提取并处理消息中的图片
      const { text: processedText, images } = formatMessageWithImages(text);
      
      // 处理Markdown格式
      if (typeof marked !== 'undefined' && (
          processedText.includes('```') || 
          processedText.includes('#') || 
          processedText.includes('*') || 
          processedText.includes('|') || 
          processedText.includes('- ') || 
          processedText.includes('1. '))) {
        contentDiv.innerHTML = marked.parse(processedText);
      } else {
        contentDiv.textContent = processedText;
      }
      
      // 如果有图片，直接在消息中显示
      if (images.length > 0) {
        const imageGallery = document.createElement('div');
        imageGallery.className = 'image-gallery';
        
        // 设置图片网格样式
        imageGallery.style.display = 'grid';
        imageGallery.style.gridTemplateColumns = images.length > 1 ? 'repeat(2, 1fr)' : '1fr';
        imageGallery.style.gap = '8px';
        imageGallery.style.marginTop = '10px';
        
        // 添加所有图片
        images.forEach((image, index) => {
          const imgContainer = document.createElement('div');
          imgContainer.className = 'image-container';
          imgContainer.style.position = 'relative';
          imgContainer.style.overflow = 'hidden';
          imgContainer.style.borderRadius = '6px';
          imgContainer.style.backgroundColor = '#f5f5f5';
          
          // 保持一定宽高比
          imgContainer.style.paddingBottom = '75%';
          
          const img = document.createElement('img');
          img.src = image.url;
          img.alt = image.description || `图片${index + 1}`;
          img.style.position = 'absolute';
          img.style.top = '0';
          img.style.left = '0';
          img.style.width = '100%';
          img.style.height = '100%';
          img.style.objectFit = 'cover';
          img.style.cursor = 'pointer';
          
          // 点击图片显示大图
          img.addEventListener('click', () => {
            showImageViewer(image.url, image.description);
          });
          
          imgContainer.appendChild(img);
          imageGallery.appendChild(imgContainer);
        });
        
        contentDiv.appendChild(imageGallery);
      }
    } else {
      // 用户消息直接显示文本
      contentDiv.textContent = text;
    }
    
    // A组合消息元素
    messageDiv.appendChild(avatarDiv);
    messageDiv.appendChild(contentDiv);
    
    chatMessages.appendChild(messageDiv);
    scrollToBottom();
  }
  
  // 显示加载状态
  function showLoading() {
    if (isLoading) return;
    isLoading = true;
    
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'message ai-message loading-message';
    
    // 添加AI头像
    const avatarDiv = document.createElement('div');
    avatarDiv.className = 'message-avatar';
    const avatarImg = document.createElement('img');
    avatarImg.src = aiAvatarUrl;
    avatarImg.alt = 'AI';
    avatarDiv.appendChild(avatarImg);
    
    // 添加加载动画
    const contentDiv = document.createElement('div');
    contentDiv.className = 'message-content loading-text';
    contentDiv.innerHTML = `
      <span>思考中</span>
      <div class="loading-dots">
        <span>.</span><span>.</span><span>.</span>
      </div>
    `;
    
    loadingDiv.appendChild(avatarDiv);
    loadingDiv.appendChild(contentDiv);
    
    chatMessages.appendChild(loadingDiv);
    scrollToBottom();
    return loadingDiv;
  }
  
  // 移除加载状态
  function removeLoading(element) {
    if (element && element.parentNode) {
      element.remove();
    }
    isLoading = false;
  }
  
  // 滚动到底部
  function scrollToBottom() {
    chatMessages.scrollTo({
      top: chatMessages.scrollHeight,
      behavior: 'smooth'
    });
  }
  
  // 检查是否有预设回答
  function checkPresetResponse(message) {
    const lowerMessage = message.toLowerCase();
    
    // 精确匹配
    if (presetResponses[message]) {
      return presetResponses[message];
    }
    
    // 关键词匹配
    for (const key in presetResponses) {
      if (lowerMessage.includes(key.toLowerCase())) {
        return presetResponses[key];
      }
    }
    
    return null;
  }
  
  // 显示数据库记录
  function displayDatabaseRecords(tableRecords) {
    // 检查是否存在记录容器
    if (!recordsContainer || !recordsContent) return;
    
    // 清空现有内容
    recordsContent.innerHTML = '';
    
    // 为每个表创建一个记录显示区域
    tableRecords.forEach(tableData => {
      const tableContainer = document.createElement('div');
      tableContainer.className = 'table-container';
      
      // 美化表名显示（将 "家电_output" 转换为 "家电"）
      let displayTableName = tableData.table_name.replace(/_output/g, '').replace(/out_put/g, '');
      
      // 添加表名
      const tableTitle = document.createElement('h4');
      tableTitle.className = 'table-title';
      tableTitle.textContent = `二手${displayTableName}商品`;
      tableContainer.appendChild(tableTitle);
      
      // 创建表格
      const table = document.createElement('table');
      table.className = 'records-table';
      
      // 创建表头
      const thead = document.createElement('thead');
      const headerRow = document.createElement('tr');
      
      // 添加表头单元格
      tableData.columns.forEach(column => {
        const th = document.createElement('th');
        // 美化列名显示
        th.textContent = formatColumnName(column);
        headerRow.appendChild(th);
      });
      
      thead.appendChild(headerRow);
      table.appendChild(thead);
      
      // 创建表体
      const tbody = document.createElement('tbody');
      
      // 添加数据行
      tableData.records.forEach(record => {
        const row = document.createElement('tr');
        
        // 添加每个单元格
        tableData.columns.forEach(column => {
          const td = document.createElement('td');
          const value = record[column];
          
          // 检查是否为图片URL
          if (value && typeof value === 'string' && 
              (value.match(/\.(jpeg|jpg|gif|png|webp)$/) || 
               value.includes('/uploads/') || 
               value.includes('http') && value.includes('img'))) {
            const img = document.createElement('img');
            img.src = value;
            img.alt = formatColumnName(column);
            img.className = 'record-image';
            img.addEventListener('click', () => {
              showImageViewer(value, `${displayTableName} - ${formatColumnName(column)}`);
            });
            td.appendChild(img);
          } else {
            // 处理普通文本，截断过长的内容
            let displayText = value;
            if (typeof value === 'string' && value.length > 50) {
              displayText = value.substring(0, 50) + '...';
              td.title = value; // 添加完整文本作为提示
            }
            td.textContent = displayText;
          }
          
          row.appendChild(td);
        });
        
        tbody.appendChild(row);
      });
      
      table.appendChild(tbody);
      tableContainer.appendChild(table);
      
      // 添加到容器
      recordsContent.appendChild(tableContainer);
    });
    
    // 显示记录容器
    recordsContainer.style.display = 'block';
    
    // 滚动到记录容器
    setTimeout(() => {
      recordsContainer.scrollIntoView({ behavior: 'smooth' });
    }, 300);
  }
  
  // 格式化列名
  function formatColumnName(column) {
    // 替换下划线为空格，首字母大写
    return column
      .replace(/_/g, ' ')
      .replace(/^\w/, c => c.toUpperCase());
  }
  
  // 处理消息发送
  async function handleSendMessage() {
    const message = chatInput.value.trim();
    if (!message || isLoading) return;
    
    // 添加用户消息
    addMessage(message, 'user');
    chatInput.value = '';
    
    // 重置输入框高度
    chatInput.style.height = 'auto';
    
    // 检查是否有预设回答
    const presetResponse = checkPresetResponse(message);
    
    if (presetResponse) {
      // 显示短暂的加载状态，模拟思考
      const loadingElement = showLoading();
      
      // 使用setTimeout模拟网络延迟，显得更自然
      setTimeout(() => {
        removeLoading(loadingElement);
        addMessage(presetResponse, 'ai');
      }, 800);
      
      return;
    }
    
    // 显示加载状态
    const loadingElement = showLoading();
    
    try {
      // 调用后端API
      const response = await fetch('/ask', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: message })
      });
      
      if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
      
      const data = await response.json();
      removeLoading(loadingElement);
      
      // 添加AI回答
      let answer = data.answer || '暂时无法回答该问题';
      addMessage(answer, 'ai');
      
      // 处理数据库记录
      if (data.table_records && data.table_records.length > 0) {
        displayDatabaseRecords(data.table_records);
      }
      
    } catch (error) {
      console.error('请求失败:', error);
      removeLoading(loadingElement);
      addMessage(`服务暂时不可用，请稍后重试`, 'error');
    }
  }
  
  // ------ 事件绑定 ------
  // 发送按钮点击
  sendButton.addEventListener('click', handleSendMessage);
  
  // 回车发送
  chatInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  });
  
  // 输入框自动增高
  chatInput.addEventListener('input', () => {
    chatInput.style.height = 'auto';
    chatInput.style.height = Math.min(chatInput.scrollHeight, 120) + 'px';
  });
  
  // 添加示例欢迎消息
  setTimeout(() => {
    addMessage('你好！我是二手商品交易助手，可以咨询我关于二手商品的问题。例如：\n\n1. 如何选择二手车？\n2. 二手手机如何判断成色？\n3. 二手电子产品需要注意什么？', 'ai');
  }, 500);
});